package com.butterfly.hotkey.starter.properties;

import com.alibaba.fastjson2.JSON;
import com.butterfly.hotkey.client.core.Refreshable;
import com.butterfly.hotkey.client.core.config.AppClientProperties;
import com.butterfly.hotkey.core.util.thread.SimpleAsyncUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 定时刷新配置信息
 *
 * @author butterfly
 */
public class HotkeyClientPropertiesRefresher implements ApplicationContextAware {

    /**
     * 配置信息的md5
     */
    private volatile String md5 = "";

    private ApplicationContext applicationContext;

    @Autowired
    private AppClientProperties clientProperties;

    /**
     * 每分钟刷新配置信息
     */
    @Scheduled(fixedDelay = 1, timeUnit = TimeUnit.MINUTES)
    public void refresh() {
        String newMd5 = DigestUtils.md5DigestAsHex(JSON.toJSONBytes(clientProperties));
        if (Objects.equals(md5, newMd5)) {
            return;
        }

        Map<String, Refreshable> beansOfType = applicationContext.getBeansOfType(Refreshable.class);
        for (Map.Entry<String, Refreshable> entry : beansOfType.entrySet()) {
            SimpleAsyncUtils.execute(() -> entry.getValue().refresh());
        }
        md5 = newMd5;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}